#!/bin/bash

# Configuration parameters
APP_DIR="${APP_DIR:-/data/metro-crawler}"  # Default path that can be overridden
LOG_DIR="${LOG_DIR:-$APP_DIR/logs}"
MAX_LOGS=7  # Keep the most recent 7 days of logs
MAX_LOG_SIZE_MB=100  # Maximum size of a single log file (MB)

# Create log directory
mkdir -p $LOG_DIR

# Clean up old log files (keep last 7 days)
find $LOG_DIR -name "ocent-crawler-*.log" -type f -mtime +$MAX_LOGS -delete

# Generate log filename (using current timestamp)
LOG_FILE="$LOG_DIR/ocent-crawler-$(date +%Y%m%d_%H%M%S).log"

# Function to check and rotate large files
check_and_rotate_log() {
    local log_file=$1
    local max_size=$((MAX_LOG_SIZE_MB * 1024 * 1024))  # Convert to bytes
    
    while true; do
        if [ -f "$log_file" ]; then
            # Check file size in a more compatible way
            if command -v stat >/dev/null 2>&1; then
                # Try both BSD and GNU stat variants
                current_size=$(stat -f%z "$log_file" 2>/dev/null || stat -c%s "$log_file" 2>/dev/null)
            else
                # Fallback to wc if stat is not available
                current_size=$(wc -c < "$log_file" 2>/dev/null || echo 0)
            fi
            
            if [ -n "$current_size" ] && [ "$current_size" -gt "$max_size" ]; then
                timestamp=$(date +%Y%m%d_%H%M%S)
                mv "$log_file" "${log_file%.log}_${timestamp}.log"
                touch "$log_file"
                echo "Log rotated at $(date)" >> "$log_file"
            fi
        fi
        sleep 300  # Check every 5 minutes
    done
}

# Switch to project directory
cd $APP_DIR || { echo "Error: Cannot change to directory $APP_DIR"; exit 1; }

# Check if node is installed
if ! command -v node >/dev/null 2>&1; then
    echo "Error: Node.js is not installed or not in PATH"
    exit 1
fi

# Ensure executable permissions
if [ -d "./node_modules/.bin" ]; then
    chmod +x ./node_modules/.bin/*
fi

# Start log checking in background
check_and_rotate_log "$LOG_FILE" &
ROTATE_PID=$!

# Cleanup function
cleanup() {
    echo "Cleaning up..."
    kill $ROTATE_PID 2>/dev/null
    exit
}

# Register cleanup function
trap cleanup EXIT INT TERM

# Use nohup to execute node command, start scheduled task
nohup node index.js --schedule > "$LOG_FILE" 2>&1 &
NODE_PID=$!

# Output log file location
echo "Ocent crawler scheduled task started in background (PID: $NODE_PID)"
echo "Logs saved to: $LOG_FILE"
echo "Use the following command to view logs:"
echo "tail -f $LOG_FILE"

# Store PID for future reference
echo $NODE_PID > "$APP_DIR/ocent-crawler.pid" 